/* eslint global-require: off, no-console: off, promise/always-return: off */

import GlobalConstant from './core/GlobalConstant';
import { setupCleanupHandlers } from './process/cleanup';
import { app, BrowserWindow, Menu, shell } from 'electron';
import * as path from 'path';
import log from 'electron-log/main';
import { resolveHtmlPath } from './utils/util';
import { setupLoggerIPC } from './handler/LoggerHandlers';
import { setupSystemHandlers } from './handler/SystemHandlers';
import { startPythonServer } from './process/pythonService';
import { setupTerminalHandlers } from './handler/TerminalHandlers';
import { setupCodeHandlers } from './handler/CodeHandlers';
import { setupSerializationHandlers } from './handler/SerializationHandlers';
import { setupPlatformioHandlers } from './handler/PlatformioHandlers';
import { setupProcessIPC } from './controller/ProcessController';
import { setupAppLifecycle } from './core/appLifecycle';
import { TerminalServiceImpl } from '../renderer/terminal-next/node/terminal.service';
import { PtyServiceManager } from '../renderer/terminal-next/node/pty.manager';
import {
  RPCTerminalServiceImpl,
  TerminalServiceClientImpl,
} from '../renderer/terminal-next/node/terminal.service.client';
import { TerminalProfileServiceNode } from '../renderer/terminal-next/node/terminal.profile.service';
import { ShellIntegrationService } from '../renderer/terminal-next/node/shell-integration.service';
import { registerTerminalIpcHandlers } from './handler/terminal-ipc';
import { NodePtyTerminalService } from '../renderer/terminal-next/browser/terminal.service';
import { AppConfig } from '../renderer/react-providers';
import { IApplicationService } from '../renderer/common/application';
import { ApplicationService } from '../renderer/common/application.service';
import { setupNotificationIPC } from './ws/socket_notification';
import { setupWebSocketIPC } from './ws/socket_message';

// 确保应用程序只运行一个实例
if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
}
// 跟踪清理函数
export const cleanupFunctions: Array<() => void> = [];

// 应用程序启动
log.info('应用程序启动中...');

function startRelevanceServerComponents(window: BrowserWindow) {
  // 设置通知 IPC
  const notificationCleanup = setupNotificationIPC(window);
  if (notificationCleanup) cleanupFunctions.push(notificationCleanup);

  // 如果需要启用WebSocket，取消下面的注释
  const webSocketCleanup = setupWebSocketIPC(window);
  if (webSocketCleanup) cleanupFunctions.push(webSocketCleanup);
}

let mainWindow: BrowserWindow | null = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support');
  sourceMapSupport.install();
}

const isDebug =
  process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';

const buildTarget = process.env.BUILD_TARGET || 'default';

if (isDebug) {
  require('electron-debug').default();
}

const installExtensions = async () => {
  const installer = require('electron-devtools-installer');
  const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
  const extensions = ['REACT_DEVELOPER_TOOLS'];

  return installer
    .default(
      extensions.map((name) => installer[name]),
      forceDownload
    )
    .catch(console.log);
};

function registerCleanup(fn: (() => void) | void) {
  if (fn) cleanupFunctions.push(fn);
}

const createWindow = (): BrowserWindow => {
  const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, 'assets')
    : path.join(__dirname, '../../assets');

  const getAssetPath = (...paths: string[]): string => {
    return path.join(RESOURCES_PATH, ...paths);
  };

  let browserWindow = new BrowserWindow({
    show: false,
    width: 1920,
    height: 1080,
    minWidth: 1280,
    minHeight: 720,
    icon: getAssetPath('icon.png'),
    frame: false,
    titleBarStyle: 'hidden',
    autoHideMenuBar: true,
    webPreferences: {
      preload: app.isPackaged
        ? path.join(__dirname, 'preload.js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),
    },
  });

  browserWindow.loadURL(resolveHtmlPath('index.html'));

  browserWindow.on('ready-to-show', () => {
    if (!browserWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      browserWindow.minimize();
    } else {
      browserWindow.show();
    }
  });

  // Open urls in the user's browser
  browserWindow.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: 'deny' };
  });

  return browserWindow;
};

function initTerminal(browserWindow: BrowserWindow) {
  const rpcTerminalService = new RPCTerminalServiceImpl(browserWindow);

  const appConfig: AppConfig = {
    workspaceDir: '',
    extWorkerHost: '',
    isElectronRenderer: true,
  };
  const applicationService: IApplicationService = new ApplicationService(
    appConfig
  );

  const shellIntegrationService = new ShellIntegrationService();
  const ptyServiceManagerRemote = new PtyServiceManager();
  const terminalServiceImplRemote = new TerminalServiceImpl(
    ptyServiceManagerRemote,
    shellIntegrationService
  );
  const terminalProfileServiceNode = new TerminalProfileServiceNode();
  const terminalServiceClient = new TerminalServiceClientImpl(
    terminalServiceImplRemote,
    terminalProfileServiceNode
  );
  terminalServiceClient.setConnectionClientId(applicationService.clientId);
  terminalServiceClient.rpcClient = [rpcTerminalService];

  const nodePtyTerminalService = new NodePtyTerminalService(
    applicationService,
    terminalServiceClient
  );

  registerTerminalIpcHandlers(nodePtyTerminalService);
}

app
  .whenReady()
  .then(async () => {
    try {
      Menu.setApplicationMenu(null);

      const browserWindow = createWindow();
      mainWindow = browserWindow;

      if (!GlobalConstant.USE_EXTERNAL_SDK) {
        const startTime = Date.now();

        startPythonServer(undefined, async () => {
          // 打印启动时间
          const endTime = Date.now(); // 记录结束时间
          const timeTaken = endTime - startTime; // 计算花费的时间
          log.info(`Python 服务器启动成功，耗时: ${timeTaken}ms`); // 打印启动时间

          setTimeout(() => {
            startRelevanceServerComponents(browserWindow);
          }, 1000);
        }); // 启动 Python 服务器并等待它完成s
      } else {
        setTimeout(() => {
          startRelevanceServerComponents(browserWindow);
        }, 1000);
      }

      if (isDebug) {
        await installExtensions();
      }

      // 设置菜单
      // const menuBuilder = new MenuBuilder(browserWindow);
      // menuBuilder.buildMenu();

      // 设置日志处理器
      registerCleanup(setupLoggerIPC());

      // 设置 IPC 处理器
      registerCleanup(setupSystemHandlers());

      //
      registerCleanup(setupTerminalHandlers());

      //
      registerCleanup(setupCodeHandlers());

      //
      registerCleanup(setupSerializationHandlers());

      //
      registerCleanup(setupPlatformioHandlers());

      // 设置处理子进程的 IPC
      registerCleanup(setupProcessIPC(browserWindow));

      // 设置应用生命周期
      registerCleanup(setupAppLifecycle(browserWindow, () => createWindow()));

      //
      initTerminal(browserWindow);

      log.info('buildTarget :', buildTarget);
    } catch (error) {
      log.error('应用程序启动失败:', error);
      app.quit();
    }
  })
  .catch(console.log);

if (!GlobalConstant.USE_EXTERNAL_SDK) setupCleanupHandlers(cleanupFunctions);
